package ma.belsoft.syga.webapp.action;

import java.util.List;

import ma.belsoft.syga.model.Marque;
import ma.belsoft.syga.service.MarqueManager;

import com.opensymphony.xwork2.Preparable;

public class MarqueAction extends BaseAction implements Preparable {
    private MarqueManager marqueManager;
    private List marques;
    private Marque marque;
    private Long id;
    private String query;

    public void setMarqueManager(MarqueManager marqueManager) {
        this.marqueManager = marqueManager;
    }

    public List getMarques() {
        return marques;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String marqueId = getRequest().getParameter("marque.id");
            if (marqueId != null && !marqueId.equals("")) {
                marque = marqueManager.get(new Long(marqueId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        marques = marqueManager.search(query, Marque.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Marque getMarque() {
        return marque;
    }

    public void setMarque(Marque marque) {
        this.marque = marque;
    }

    public String delete() {
        marqueManager.remove(marque.getId());
        saveMessage(getText("marque.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            marque = marqueManager.get(id);
        } else {
            marque = new Marque();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (marque.getId() == null);

        marqueManager.save(marque);

        String key = (isNew) ? "marque.added" : "marque.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}